package com.qywx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qywx.dao.DepartmentDao;
import com.qywx.dao.TagDao;
import com.qywx.dao.TagRuleDao;
import com.qywx.dao.UserDao;
import com.qywx.entity.DepartmentEntity;
import com.qywx.entity.TagEntity;
import com.qywx.entity.UserEntity;
import com.qywx.entity.UserTagEntity;
import com.qywx.service.TagService;
import com.qywx.service.UserService;
import com.qywx.utils.R;
import com.qywx.utils.RestTemplateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName UserServiceImpl
 * @Description: 成员service
 * @Author wmj
 * @Date 2020/3/4
 * @Version V1.0
 **/
@Service("userService")
public class UserServiceImpl implements UserService {
    private final static Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class);
    @Autowired
    UserDao userDao;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    TagDao tagDao;

    @Autowired
    TagRuleDao tagRuleDao;

    @Autowired
    TagService tagService;

    @Autowired
    DepartmentDao departmentDao;

    @Transactional
    @Override
    public R saveUser(UserEntity user) {
        if (user.getUserid() == null) {
            R.error("请输入用户账号");
        }
        if (user.getName() == null) {
            R.error("请输入用户姓名");
        }
        //人员类型：1=内部人员，2=外部人员
        String usertype = user.getUsertype();
        if ("1".equals(usertype)) {
            if (user.getDepartment() == null) {
                R.error("请选择用户所属部门");
            }
        }
        String mobile = user.getMobile();
        String email = user.getEmail();
        if (StringUtils.isEmpty(mobile) && StringUtils.isEmpty(email)) {
            return R.error("手机号和email不能同时为空");
        }
        if (!StringUtils.isEmpty(mobile)) {
            int length = mobile.length();
            if (11 != length) {
                return R.error("请输入正确的手机号，长度不对");
            }
        }
        //判断用户是否已存在
        UserEntity userEntity = userDao.selectById(user.getUserid());
        if (userEntity == null) {//不存在
            //是否同步到微信 0:未同步 1:已同步 2：待更新
            user.setIsSynchronize("0");
            user.setStatus(4);
            //保存成员与部门关系
            if ("1".equals(usertype)) {
                String departments = user.getDepartment();
                saveDepartUser(departments, user.getUserid());
            }
            //保存用户
            user.setCreatTime(new Date());
            userDao.insert(user);
        } else {//存在
            return R.error("成员已存在");
        }
        //内部人员同步到企业微信
        if ("1".equals(usertype)) {
            saveToWechat(user);
        }
        return R.ok();
    }


    //保存用户到微信
    @Override
    public R saveToWechat(UserEntity userEntity) {
        //成员部门中间表 根据成员id获取部门id集合
        List<Integer> depList = userDao.selDepIdByUserid(userEntity.getUserid());
        String avatarMediaid = userEntity.getAvatarMediaid();
        String accessToken = restTemplateUtil.getaccessToken();
        if (accessToken != null) {
            //保存用户到企业微信
            String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + accessToken;
            JSONObject jsonObj = (JSONObject) JSONObject.toJSON(userEntity);
            jsonObj.put("avatar_mediaid", avatarMediaid);
            jsonObj.put("department", depList);
            Map map = new HashMap();
            map.put("工号",userEntity.getUserNumber());
            map.put("科室",userEntity.getDepartmentOffice());
            map.put("科室代码",userEntity.getOfficeNumber());
            JSONObject jsonObject = splicingExtendedFields(map);
            jsonObj.put("extattr",jsonObject);
            //科室代码
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //请求体
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg") + "===========" + code;
            log.info("===========保存用户到微信返回信息===========" + errmsg, errmsg);
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\log.txt"),true);
                String message = userEntity.getUserid() + "======" + new Date() + "============" + errmsg;
                fileOutputStream.write(message.getBytes());
                fileOutputStream.write("\r\n".getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (0 == code) {
                //同步到微信成功，更新isSynchroniz为1:0:未同步 1:已同步 2：待更新
                userEntity.setIsSynchronize("1");
                userEntity.setStat(1);
                userEntity.setSyncTime(new Date());
                userDao.updateById(userEntity);
                return R.ok();
            } else {
                return R.error("一键同步到微信失败");
            }
        } else {
            return R.error("获取access_token失败");
        }
    }

    public JSONObject splicingExtendedFields(Map map) {
        //扩展字段
        JSONObject jsonObject2 = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for(Object key : map.keySet()){
            //json数组
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("type",0);
            jsonObject3.put("name",key);
            JSONObject jsonObject4 = new JSONObject();
            jsonObject3.put("text",jsonObject4);
            jsonObject4.put("value",map.get(key));
            jsonArray.add(jsonObject3);
        }
        jsonObject2.put("attrs",jsonArray);
        return jsonObject2;
    }

    @Override
    public List<UserEntity> findByName(String name, int depid, String usertype, String stat, String status,String id,String category,String gender) {
        //递归获取本部门及子部门的部门id
       /* List<Integer> list = new ArrayList<>();
        list.add(depid);
        List depId1 = getDepId(list);*/
        //long depId = depid;
        //判断是否是部门管理员
        List<UserEntity> userEntity;
        if (0 == depid) {
            //查所有人员
            userEntity = userDao.findByNameAll(name, usertype, stat, status,id,category,gender);
        } else {
            //部门管理员查该部门下人员
            userEntity = userDao.findByName(name, depid,id,category,gender);
        }
        return userEntity;
    }

    public List getDepId(List<Integer> list) {
        if (list.size() < 0) {
            return new ArrayList();
        } else {
            List array = new ArrayList();
            for (int i = 0; i < list.size(); i++) {
                List<Integer> idList = departmentDao.findChildDepId(list.get(i));
                array.addAll(idList);
                List depId = getDepId(idList);
                array.addAll(depId);
            }
            return array;
        }
    }

    @Override
    @Transactional
    public R updateUser(UserEntity user) {
        //成员类型：1=内部人员，2=外部人员
        String usertype = user.getUsertype();
        if (usertype == null) {
            return R.error("请选择内部人员还是外部人员");
        }
        if ("1".equals(usertype)) {//内部人员
            //删除用户所在部门
            userDao.deleteDepUser(user.getUserid());
            //保存用户所在部门
            String departments = user.getDepartment();
            saveDepartUser(departments, user.getUserid());
            UserEntity userEntity = userDao.selectById(user.getUserid());
            user.setStatus(userEntity.getStatus());
            //更新到微信
            userDao.updateById(user);
            updateWechat(user);
            return R.ok();
        } else {//外部人员
            userDao.updateById(user);
            return R.ok();
        }
    }
    @Override
    public R updateThisPlatformUser(UserEntity user) {
        //成员类型：1=内部人员，2=外部人员
        String usertype = user.getUsertype();
        if (usertype == null) {
            return R.error("请选择内部人员还是外部人员");
        }
        if ("1".equals(usertype)) {//内部人员
            //删除用户所在部门
            userDao.deleteDepUser(user.getUserid());
            //保存用户所在部门
            String departments = user.getDepartment();
            saveDepartUser(departments, user.getUserid());
            UserEntity userEntity = userDao.selectById(user.getUserid());
            user.setStatus(userEntity.getStatus());
            user.setStat(1);
            //更新到微信
            userDao.updateById(user);
            return R.ok();
        } else {//外部人员
            userDao.updateById(user);
            return R.ok();
        }
    }

    @Override
    public R updateWechatUser(UserEntity user) {
        updateWechat(user);
        return R.ok();
    }

    @Override
    public String trans(String department) {
        String[] split = department.split(",");
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            DepartmentEntity departmentEntity = departmentDao.selById(Integer.valueOf(split[i]));
            if(departmentEntity!=null){
                stringBuffer.append(departmentEntity.getName()).append("/");
            }
        }
        String str = stringBuffer.toString();
        String depName = str.substring(0, str.length() - 1);
        return depName;
    }

    @Override
    @Transactional
    //批量删除用户
    public R delUserByUserIds(String userId, String usertype) {
        if ("1".equals(usertype)) {//内部人员
            String[] str = userId.split(",");
            List<String> idList = Arrays.asList(str);
            //批量删除用户：做逻辑删除
            userDao.deleteBatchId(idList);
            //批量删除成员标签关系
            tagDao.delUserTad(idList);
            //批量刪除成员部门关系
            userDao.delUserDep(idList);
            //同步删除微信端
            String accessToken = restTemplateUtil.getaccessToken();
            String url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("useridlist", idList);
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //请求体
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
            //发起请求
            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========删除微信用户返回信息===========" + errmsg, errmsg);
            if (0 != code) {
                R.error("删除微信用户失败");
            }
            return R.ok();
        } else {//外部人员
            String[] str = userId.split(",");
            List<String> idList = Arrays.asList(str);
            //批量删除用户：做逻辑删除
            userDao.deleteBatchId(idList);
            return R.ok();
        }
    }

    @Override
    public R findByDepartmentId(String departmentId, int page, int size, String status) {
        if (page < 1) {
            page = 1;
        }
        if (size < 1) {
            size = 10;
        }
        int start = (page - 1) * size;
        int depid = Integer.valueOf(departmentId);
        List<UserEntity> userEntities = userDao.findByDepartmentId(depid, start, size, status);
        for (int i = 0; i < userEntities.size(); i++) {
            UserEntity userEntity = userEntities.get(i);
            //获取用户所在部门的名称
            List<String> list = userDao.findByUserid(userEntity.getUserid());
            StringBuffer str = new StringBuffer();
            for (int j = 0; j < list.size(); j++) {
                str.append(list.get(j)).append("/");
            }
            String depName = str.toString().substring(0, str.length() - 1);
            userEntity.setDepName(depName);
            String tagName = getTagName(userEntity.getUserid());
            userEntity.setTagName(tagName);
        }
        String total = userDao.getTotal(departmentId, status);
        R r = new R();
        r.put("total", total);
        r.put("data", userEntities);
        return r;
    }

    @Override
    public R findByUserid(String userid) {
        //获取成员信息
        UserEntity userEntity = userDao.selectDetailById(userid);
        //获取成员类型
        String usertype = userEntity.getUsertype();
        if ("1".equals(usertype)) {//内部人员
            //获取用户所在部门的名称
            int stat = userEntity.getStat();
            if (1 == stat || 2 == stat) {//有效人员
                List<String> list = userDao.findByUserid(userid);
                StringBuffer str = new StringBuffer();
                for (int i = 0; i < list.size(); i++) {
                    str.append(list.get(i)).append("/");
                }
                String depName = str.toString().substring(0, str.length() - 1);
                //获取用户的所有标签名称
                String tagName = getTagName(userid);
                String[] split = tagName.split("/");
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < split.length; i++) {
                    String tag = split[i];
                    if (!"".equals(tag)) {
                        TagEntity tagEntity = tagDao.selectByName(tag);
                        Long tagId = tagEntity.getTagid();
                        stringBuffer.append(tagId).append(",");
                    }
                }
                String tagid = stringBuffer.toString();
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(userEntity);
                jsonObject.put("depName", depName);
                jsonObject.put("tagName", tagName);
                jsonObject.put("tagid", tagid);
                return new R().put("data", jsonObject);
            } else {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(userEntity);
                return new R().put("data", jsonObject);
            }
        } else {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(userEntity);
            return new R().put("data", jsonObject);
        }
    }

    //根据部门id列表获取所有部门名称
    public String getDepNameById(String departmentId) {
        if (departmentId.contains(",")) {
            String[] department = departmentId.split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < department.length; i++) {
                //获取部门名称
                if (StringUtils.isNotEmpty(department[i])) {
                    String name = userDao.findNameById(department[i]);
                    //拼接所属部门名称
                    if (name != null) {
                        stringBuffer.append(name).append("/");
                    }
                }
            }
            String name = stringBuffer.toString();
            if (name.endsWith("/")) {
                name = name.substring(0, name.length() - 1);
            }
            return name;
        } else {
            //获取部门名称
            String name = userDao.findNameById(departmentId);
            return name;
        }
    }

    //获取所有标签名称
    public String getTagName(String userid) {
        List<TagEntity> tagNameList = userDao.getTagName(userid);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < tagNameList.size(); i++) {
            TagEntity tagEntity = tagNameList.get(i);
            String name = tagEntity.getTagname();
            stringBuffer.append("/").append(name);
        }
        String tagName = stringBuffer.toString();
        return tagName;
    }

    @Override
    public R exchangeDepartment(String departmentId, String userid) {
        if (departmentId == null) {
            R.error("请选择部门");
        }
        userDao.exchangeDepartment(departmentId, userid);
        return R.ok();
    }

    @Override
    public R asynchronousDetection() {
        String count = userDao.asynchronousDetection();
        return R.ok(count);
    }

    @Override
    //@Async
    public R synchronize() {
        Thread t = new Thread(()->{
            log.info("==========线程开始");
            List<UserEntity> userEntityList = userDao.synchronize();
            for (int i = 0; i < userEntityList.size(); i++) {
                UserEntity userEntity = userEntityList.get(i);
                String isSynchronize = userEntity.getIsSynchronize();
                if ("0".equals(isSynchronize)) {
                    saveToWechat(userEntity);
                } else {
                    updateWechat(userEntity);
                }
            }
            log.info("=============线程结束");
        });
        t.start();
        return R.ok();
    }

    @Override
    public List<UserEntity> export(String id) {
        //根据部门id查询部门成员
        List<UserEntity> userEntityList = userDao.export(id);
        //循环获取成员
        for (int i = 0; i < userEntityList.size(); i++) {
            UserEntity userEntity = userEntityList.get(i);
            List<String> list = userDao.findByUserid(userEntity.getUserid());
            StringBuffer str = new StringBuffer();
            for (int j = 0; j < list.size(); j++) {
                str.append(list.get(j)).append("/");
            }
            String depName = str.toString().substring(0, str.length() - 1);
            userEntity.setDepName(depName);
        }
        return userEntityList;
    }

    @Override
    public R findUser(int page, int size, String usertype) {
        if (page < 1) {
            page = 1;
        }
        if (size < 1) {
            size = 10;
        }
        if ("1".equals(usertype)) {
            int start = (page - 1) * size;
            List<UserEntity> userEntityList = userDao.findUser(start, size);
            for (int i = 0; i < userEntityList.size(); i++) {
                UserEntity userEntity = userEntityList.get(i);
                int stat = userEntity.getStat();
                if (1 == stat) {
                    List<String> list = userDao.findByUserid(userEntity.getUserid());
                    StringBuffer str = new StringBuffer();
                    for (int j = 0; j < list.size(); j++) {
                        str.append(list.get(j)).append("/");
                    }
                    String depName = str.toString().substring(0, str.length() - 1);
                    userEntity.setDepName(depName);
                }
            }
            String total = userDao.getTotalAll();
            R r = new R();
            r.put("data", userEntityList);
            r.put("total", total);
            return r;
        } else {
            int start = (page - 1) * size;
            List<UserEntity> userEntityList = userDao.findUserWai(start, size);
            String total = userDao.getTotalAllWai();
            R r = new R();
            r.put("data", userEntityList);
            r.put("total", total);
            return r;
        }
    }

    @Override
    @Transactional
    public R save(List<UserEntity> list) {
        for (UserEntity user : list) {
            UserEntity userEntity = new UserEntity();
            String name = user.getName();
            userEntity.setName(name);
            String userid = user.getUserid();
            userEntity.setUserid(userid);
            if (null != user.getAlias()) {
                userEntity.setAlias(user.getAlias());
            }
            if (null != user.getPosition()) {
                userEntity.setPosition(user.getPosition());
            }
            userEntity.setEnable("1");
            if ("男".equals(user.getGender())) {
                userEntity.setGender("1");
            } else if ("女".equals(user.getGender())) {
                userEntity.setGender("2");
            }
            userEntity.setMobile(user.getMobile());
            if (user.getTelephone() != null) {
                userEntity.setTelephone(user.getTelephone());
            }
            if (user.getEmail() != null) {
                userEntity.setEmail(user.getEmail());
            }
            if (user.getAddress() != null) {
                userEntity.setAddress(user.getAddress());
            }
            userEntity.setIsSynchronize("0");
            userEntity.setUserNumber(user.getUserNumber());
            userEntity.setAttribute1(user.getAttribute1());
            userEntity.setAttribute2(user.getAttribute2());
            userEntity.setAttribute3(user.getAttribute3());
            userEntity.setAttribute4(user.getAttribute4());
            userEntity.setAttribute5(user.getAttribute5());
            userEntity.setAttribute6(user.getAttribute6());
            userEntity.setAttribute7(user.getAttribute7());
            userEntity.setAttribute8(user.getAttribute8());
            userEntity.setAttribute9(user.getAttribute9());
            userEntity.setAttribute10(user.getAttribute10());
            //处理用户部门
            String depName = user.getDepName();
            String[] depNames = depName.split("/");
            StringBuffer department = new StringBuffer();
            for (int i = 0; i < depNames.length; i++) {
                //根据部门名称获取部门id
                if (depNames[i] != null && !"".equals(depNames[i])) {
                    Integer departmentId = userDao.findDepartByDepName(depNames[i]);
                    userDao.saveDepUser(departmentId, userid);
                    department.append(departmentId).append(",");
                }
            }
            String departmentId = department.toString();
            userEntity.setDepartment(departmentId);
            userEntity.setStat(1);
            userEntity.setStatus(4);
            userEntity.setUsertype("1");
            userEntity.setCreatTime(new Date());
            userDao.insert(userEntity);
            //同步到微信端
            saveToWechat(userEntity);
            UserEntity entity = userDao.selectById(userid);
            //属性一到属性十匹配
           List<Long> datas = tagRuleDao.selectByAttribute1(entity);
            //save user tag
            if(datas != null && datas.size() != 0){
                datas.stream().forEach(r->{
                    tagService.saveTagUser(r,entity.getUserid());
                });
            }
        }
        return R.ok();
    }

    @Override
    public List<UserEntity> exportByUserId(String userid, String usertype) {
        List<UserEntity> userEntityList = new ArrayList<>();
        if (StringUtils.isEmpty(userid) || "".equals(userid)) {
            //获取所有成员
            userEntityList = userDao.exportByUserId(userid, usertype);
            //循环获取成员
            for (int i = 0; i < userEntityList.size(); i++) {
                UserEntity userEntity = userEntityList.get(i);
                int stat = userEntity.getStat();
                if ("1".equals(usertype)) {//内部成员
                    List<String> list = userDao.findByUserid(userEntity.getUserid());
                    StringBuffer str = new StringBuffer();
                    for (int j = 0; j < list.size(); j++) {
                        str.append(list.get(j)).append("/");
                    }
                    String depName = str.toString().substring(0, str.length() - 1);
                    userEntity.setDepName(depName);
                }
            }
        } else {
            String[] split = userid.split(",");
            List<String> useridlist = Arrays.asList(split);
            userEntityList = userDao.selectBatchIds(useridlist);
            for (int i = 0; i < userEntityList.size(); i++) {
                UserEntity userEntity = userEntityList.get(i);
                int stat = userEntity.getStat();
                if (1 == stat) {//有效成员
                    if("1".equals(usertype)){//内部成员
                        List<String> list = userDao.findByUserid(userEntity.getUserid());
                        StringBuffer str = new StringBuffer();
                        for (int j = 0; j < list.size(); j++) {
                            str.append(list.get(j)).append("/");
                        }
                        String depName = str.toString().substring(0, str.length() - 1);
                        userEntity.setDepName(depName);
                    }
                }
            }
        }
        return userEntityList;
    }

    @Override
    public R invite(String userid) {
        String accessToken = restTemplateUtil.getaccessToken();
        //去微信端查询部门成员是否存在（防止存入用户未同步到微信，直接更新用户）
        String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + userid;
        Map resultMap = restTemplate.getForObject(getUrl, Map.class);
        Integer code = (Integer) resultMap.get("errcode");
        if (0 != code) {
            return R.error("成员不存在微信端，请先保存用户到微信端");
        } else {
            int status = (int) resultMap.get("status");//激活状态: 1=已激活，2=已禁用，4=未激活
            if (1 == status) {
                userDao.updateStatus(userid);
                return R.ok("已激活企业微信或已关注微工作台");
            } else if (2 == status) {
                return R.ok("微信端已禁用");
            } else {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/invite?access_token=" + accessToken;
                Map map = restTemplateUtil.postStringRequest(url, userid);
                Integer errcode = (Integer) map.get("errcode");
                String errmsg = (String) map.get("errmsg");
                if (0 == errcode) {
                    return R.ok("已邀请");
                } else {
                    log.info("===========邀请失败===========" + errmsg, errmsg);
                    return R.error("邀请失败");
                }
            }
        }
    }

    @Override
    @Transactional
    public R addUserTag(String userid, String tagids) {
        if (tagids == null || "".equals(tagids)) {
            return R.ok();
        }
        if (tagids.contains(",")) {
            String[] tagIds = tagids.split(",");
            for (int i = 0; i < tagIds.length; i++) {
                String tagid = tagIds[i];
                if (tagid != null && !"".equals(tagid)) {
                    long tagId = Long.parseLong(tagid);
                    UserTagEntity userTagEntity = tagDao.selByUseridAandTagid(userid, tagId);
                    if (userTagEntity == null) {
                        userDao.saveTagUser(tagId, userid);
                        //同步增加到微信
                        String accessToken = restTemplateUtil.getaccessToken();
                        if (accessToken != null) {
                            String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=" + accessToken;
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("tagid", tagId);
                            List<String> list = Arrays.asList(userid);
                            jsonObject.put("userlist", list);
                            //设置请求头
                            HttpHeaders headers = new HttpHeaders();
                            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                            headers.setContentType(type);
                            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                            //请求体
                            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
                            //发起请求
                            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
                            Integer code = (Integer) resultMap.get("errcode");
                            String errmsg = (String) resultMap.get("errmsg");
                            log.info("===========保存标签用户到微信返回信息===========" + errmsg, errmsg);
                            if (0 != code) {
                                return R.error("保存用户标签到微信失败");
                            }
                        } else {
                            return R.error("获取access_token失败");
                        }
                    }
                }
            }
        } else {
            long tagId = Long.parseLong(tagids);
            userDao.saveTagUser(tagId, userid);
        }
        return R.ok();
    }

    @Override
    public R getMobile(String mobile) {
        String mob = userDao.getMobile(mobile);
        if (mobile != null && !"".equals(mobile)) {
            return R.error("手机号已存在");
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R updateUserTag(String userid, String delTagid, String saveTagid) {
        if (delTagid != null && !"".equals(delTagid)) {
            //循环删除成员标签
            String[] tagid = delTagid.split(",");
            for (int i = 0; i < tagid.length; i++) {
                long tagId = Long.parseLong(tagid[i]);
                tagDao.delTagUser(tagId, userid);
                //同步删除微信端
                String accessToken = restTemplateUtil.getaccessToken();
                if (accessToken != null) {
                    String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers?access_token=" + accessToken;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("tagid", tagId);
                    List<String> list = Arrays.asList(userid);
                    jsonObject.put("userlist", list);
                    //设置请求头
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                    //请求体
                    HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
                    //发起请求
                    Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
                    Integer code = (Integer) resultMap.get("errcode");
                    String errmsg = (String) resultMap.get("errmsg");
                    log.info("===========删除微信端用户标签返回信息===========" + errmsg, errmsg);
                    if (0 != code) {
                        return R.error("删除微信端用户标签");
                    }
                } else {
                    return R.error("获取access_token失败");
                }
            }
        }

        if (saveTagid != null && !"".equals(saveTagid)) {
            //循环新增成员标签
            String[] save = saveTagid.split(",");
            for (int i = 0; i < save.length; i++) {
                long tagId = Long.parseLong(save[i]);
                tagDao.saveTagUser(tagId, userid);
                String accessToken = restTemplateUtil.getaccessToken();
                if (accessToken != null) {
                    String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=" + accessToken;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("tagid", tagId);
                    List<String> list = Arrays.asList(userid);
                    jsonObject.put("userlist", list);
                    //设置请求头
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                    //请求体
                    HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
                    //发起请求
                    Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
                    Integer code = (Integer) resultMap.get("errcode");
                    String errmsg = (String) resultMap.get("errmsg");
                    log.info("===========保存用户标签到微信返回信息===========" + errmsg, errmsg);
                    if (0 != code) {
                        return R.error("保存用户标签到微信失败");
                    }
                } else {
                    return R.error("获取access_token失败");
                }
            }
        }
        return R.ok();
    }

    @Override
    public R findUserCondition(int page, int size, String usertype, String stat, String status) {
        if (page < 1) {
            page = 1;
        }
        if (size < 1) {
            size = 10;
        }
        if ("1".equals(usertype)) {//内部人员
            int start = (page - 1) * size;
            List<UserEntity> userEntityList = userDao.findUserCondition(start, size, stat, status);
            for (int i = 0; i < userEntityList.size(); i++) {
                UserEntity userEntity = userEntityList.get(i);
                int st = userEntity.getStat();
                if (1 == st) {//有效
                    List<String> list = userDao.findByUserid(userEntity.getUserid());
                    StringBuffer str = new StringBuffer();
                    for (int j = 0; j < list.size(); j++) {
                        str.append(list.get(j)).append("/");
                    }
                    String s = str.toString();
                    String depName = null;
                    if (!"".equals(s) && null != s) {
                        depName = s.substring(0, str.length() - 1);
                    }

                    //获取用户的所有标签名称
                    String tagName = getTagName(userEntity.getUserid());
                    userEntity.setDepName(depName);
                    userEntity.setTagName(tagName);
                }
            }
            String total = userDao.getTotalAllCondition(stat, status);
            R r = new R();
            r.put("data", userEntityList);
            r.put("total", total);
            return r;
        } else {
            int start = (page - 1) * size;
            List<UserEntity> userEntityList = userDao.findUserWaiCondition(start, size, stat);
            String total = userDao.getTotalAllWaiCondition(stat);
            R r = new R();
            r.put("data", userEntityList);
            r.put("total", total);
            return r;
        }
    }

    @Override
    @Transactional
    public R updateStat(String userid) {
        //将用户设置为有效
        userDao.updateStat1(userid);
        //报错用户部门关系
        String department = "1";
        saveDepartUser(department, userid);
        UserEntity userEntity = userDao.selectById(userid);
        saveToWechat(userEntity);
        return R.ok();
    }

    //保存用户部门关系
    public void saveDepartUser(String departments, String userid) {
        String[] department = departments.split(",");
        for (int i = 0; i < department.length; i++) {
            String dep = department[i];
            if (!"".equals(dep)) {
                int depart = Integer.valueOf(dep);
                userDao.saveDepUser(depart, userid);
            }
        }
    }

    //更新微信端用户
    public void updateWechat(UserEntity userEntity) {
        String accessToken = restTemplateUtil.getaccessToken();
        String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + userEntity.getUserid();
        Map map = restTemplate.getForObject(getUrl, Map.class);
        String userid = (String) map.get("userid");
        if (StringUtils.isNotEmpty(userid)) {
            JSONObject jsonObj = (JSONObject) JSONObject.toJSON(userEntity);
            List<Long> depList = new ArrayList<>();
            List<String> depId = userDao.findDepartmentId(userEntity.getUserid());
            for (int i = 0; i < depId.size(); i++) {
                String s = depId.get(i);
                if (!"".equals(s)) {
                    depList.add(Long.parseLong(s));
                }
            }
            jsonObj.put("department", depList);
            //英文名填工号
            Map mapxEtended = new HashMap();
            mapxEtended.put("工号",userEntity.getUserNumber());
            mapxEtended.put("科室",userEntity.getDepartmentOffice());
            mapxEtended.put("科室代码",userEntity.getOfficeNumber());
            JSONObject jsonObject = splicingExtendedFields(mapxEtended);
            jsonObj.put("extattr",jsonObject);
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //请求体
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
            String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + accessToken;
            Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
            String errmsg = (String) resultMap.get("errmsg");
            log.info("===========更新微信返回信息===========" + errmsg, errmsg);
            Integer code = (Integer) resultMap.get("errcode");
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\log.txt"),true);
                String message = userEntity.getUserid() + "======" + new Date() + "============" + errmsg + "===========" + code;
                fileOutputStream.write(message.getBytes());
                fileOutputStream.write("\r\n".getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (0 == code) {
                userEntity.setIsSynchronize("1");
                userEntity.setStat(1);
                userDao.updateById(userEntity);
            } else {
                userEntity.setIsSynchronize("2");
                userDao.updateById(userEntity);
            }
        } else {
            saveToWechat(userEntity);
        }
    }
}
